package com.yyg.ssm.web;

import com.yyg.ssm.domain.User;
import com.yyg.ssm.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * @Author: 一一哥
 * @Blame: yyg
 * @Since: Created in 2021/1/6
 * @Description: $cursor$
 */
@Controller
public class LoginController {

    //@Autowired
    //private UserService userService;

    @PostMapping("/login")
    public String login(User user) {
        //User result = userService.login(user);

        //Subject:代表当前要登录的用户
        Subject subject = SecurityUtils.getSubject();
        //构建了一个用户名密码令牌
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());

        try {
            //执行登录,传递token
            subject.login(token);
        } catch (AuthenticationException e) {
            //认证异常
            e.printStackTrace();
            return "error";
        }

        if (subject.isAuthenticated()) {
            //认证成功
            return "home";
        } else {
            //清空令牌信息
            token.clear();
            return "redirect:/login.jsp";
        }
    }

    @GetMapping("/logout")
    public String logout() {
        //清除session
        Subject subject = SecurityUtils.getSubject();
        //Session session = subject.getSession();
        //session.removeAttribute("user");
        if(subject!=null){
            subject.logout();
        }

        return "redirect:/index.jsp";
    }

}
